<script lang="ts" setup>
import { defineProps, reactive, defineEmits, ref, PropType, watch, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { DistributionEnum } from '@/consts/Customer'
import { EnumType } from '@/consts/public'
import { getProducts, Products } from '@/api/products'
import { addCustomer, setCustomerMessage, Customer, CustomerOptionParam } from '@/api/customer'
import { mapSuggestion, Address } from '@/api/qqMap'
import { getAllMilkman, Milkman } from '@/api/milkman'

const distributionEnumList: EnumType[] = Object.values(DistributionEnum)
const emit = defineEmits(['closeDialog', 'optionSuccess'])

const props = defineProps({
  showAddDialog: {
    type: Boolean,
    default: false
  },
  defaultRuleForm: {
    type: Object as PropType<Customer>,
    default: () => ({})
  },
  dialogType: {
    validator (value: string) {
      return ['add', 'set'].includes(value)
    },
    default: 'add'
  }
})

const isSet = computed(() => props.dialogType === 'set')
const typeText = computed(() => {
  if (isSet.value) {
    return '修改'
  } else {
    return '添加'
  }
})

// 表单信息
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<CustomerOptionParam>({
  name: '',
  amount: 30,
  products_name: '',
  product_coding: '',
  phone: '',
  distribution: '',
  start_time: '',
  address: '',
  address_obj: '',
  detailed_address: '',
  milkman_id: ''
})

const rules = reactive({
  name: [
    { required: true, message: '用户名不能为空', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '手机号不能为空', trigger: 'blur' },
    { pattern: /^((0\d{2,3}-\d{7,8})|(1[3456789]\d{9}))$/, message: '请输入合法手机号/电话号', trigger: 'blur' }
  ],
  products_name: [
    {
      required: true,
      message: '请选择订购产品',
      trigger: 'change'
    }
  ],
  amount: [
    {
      required: true,
      message: '请输入订购瓶数量',
      trigger: 'blur'
    }
  ],
  distribution: [
    {
      required: true,
      message: '请选择订购瓶方式',
      trigger: 'change'
    }
  ],
  start_time: [
    {
      type: 'date',
      required: true,
      message: '请选择配送时间',
      trigger: 'change'
    }
  ],
  address: [
    {
      required: true,
      message: '请输选择配送地址',
      trigger: 'change'
    }
  ],
  detailed_address: [
    {
      required: true,
      message: '请输输入详细地址',
      trigger: 'blur'
    }
  ]
})

const submitForm = async () => {
  if (!ruleFormRef.value) return
  try {
    await ruleFormRef.value.validate()
  } catch {
    return
  }
  try {
    isSet.value ? await setCustomerMessage({ ...ruleForm }) : await addCustomer({ ...ruleForm })
    ElMessage.success(typeText.value + '成功')
    emit('optionSuccess')
  } catch (error) {
    ElMessage.error((error as Error).message)
  }
}

// 订购产品列表
const state = ref<Products | string>()

// 这里不能用 async await 会报 error.ts?aa5c:9 Uncaught (in promise) ElementPlusError: [ElAutocomplete] autocomplete suggestions must be an array
const querySearchAsync = (queryString: string, cb: (arg: Products[]) => void) => {
  getProducts({ name: queryString }).then((res: Products[]) => {
    cb(res)
  }).catch(
    err => console.log(err)
  )
}
const handleSelect = (product: Products) => {
  ruleForm.products_name = product.name
  ruleForm.product_coding = product.coding
}

// 推荐地址
const suggestionAddress = ref<Address | string>()
const queryAddress = (queryString: string, cb: (arg: Address[]) => void) => {
  mapSuggestion({ keyword: queryString }).then((res: Address[]) => {
    cb(res)
  }).catch(
    err => console.log(err)
  )
}
const selectAddress = (address: Address) => {
  ruleForm.address = address.title
  ruleForm.address_obj = JSON.stringify(address)
}

// const selectedOptions = ref()
// const handleChange = async (value) => {
//   console.log(value)
//   const aaa = await search()
//   console.log(aaa)
// }

watch(() => props.defaultRuleForm, async (now) => {
  if (isSet.value) {
    Object.assign(ruleForm, now)
    state.value = now.products_name
    suggestionAddress.value = now.address
  }
}, { immediate: true })

const milkMansList = ref<Milkman[]>()
onMounted(async () => {
  milkMansList.value = await getAllMilkman()
})

</script>
<template>
  <el-dialog
    :model-value="props.showAddDialog"
    :title="typeText + '客户信息'"
    width="40%"
    :before-close="() => emit('closeDialog')"
  >
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="客户名" prop="name">
        <el-input v-model="ruleForm.name" />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="ruleForm.phone" />
      </el-form-item>
      <el-form-item label="订购产品" prop="products_name">
        <el-autocomplete
          v-model="state"
          value-key="name"
          :fetch-suggestions="querySearchAsync"
          @select="handleSelect"
        />
      </el-form-item>
      <el-form-item label="订购瓶数" prop="amount">
        <el-input v-model="ruleForm.amount" type='number'/>
      </el-form-item>
      <el-form-item label="起送时间" prop="start_time">
       <el-date-picker v-model="ruleForm.start_time" type="date" />
      </el-form-item>
      <el-form-item label="配送方式" prop="distribution">
        <el-select v-model="ruleForm.distribution">
          <el-option
            v-for="item in distributionEnumList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="送奶工">
        <el-select v-model="ruleForm.milkman_id">
          <el-option
            v-for="item in milkMansList"
            :key="item.id"
            :label="item.user_name"
            :value="item.id"
            ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="配送地址" prop="address">
        <el-autocomplete
          v-model="suggestionAddress"
          :fetch-suggestions="queryAddress"
          @select="selectAddress"
          value-key="title"
        >
        <template #default="{item}">
            <span>{{ item.title }}</span>
            <span class="suggestions-address">{{ item.address }}</span>
          </template>
        </el-autocomplete>
      </el-form-item>
      <el-form-item label="详细地址" prop="detailed_address" >
        <el-input
          type="textarea"
          v-model="ruleForm.detailed_address"
          :autosize="{ minRows: 3, maxRows: 6 }"
        />
      </el-form-item>
      <!-- <el-form-item label="配送地址">
        <el-cascader
          placeholder="请选择地区"
            size="default"
            :options="regionData"
            v-model="selectedOptions"
            @change="handleChange"
          ></el-cascader>
      </el-form-item> -->
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="emit('closeDialog')">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
.dialog-footer button:first-child {
  margin-right: 10px;
}
.demo-ruleForm {
  width: 90%;
}
.suggestions-address {
  margin-left: 5px;
  color: #898989;
  font-size: 12px
}
</style>
